package com.white.algebra.dao.impl;

import com.white.algebra.dao.SysLogDao;
import com.white.algebra.domain.Syslog;
import com.white.algebra.domain.UserInfo;
import com.white.algebra.utils.JdbcUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class SysLogDaoImpl implements SysLogDao {
    @Override
    public void addSysLog(Syslog sysLog) throws SQLException {
        QueryRunner qr = new QueryRunner(JdbcUtil.getDataSource());
        String sql = "INSERT INTO syslog (`visitTime`,`username`, `ip`,`url`,`executionTime`,`method`) VALUES (?, ?, ?,?,?,?)";
        Object[] params = {sysLog.getVisitTime(),sysLog.getUsername(),sysLog.getIp(),sysLog.getUrl(),sysLog.getExecutionTime(),sysLog.getMethod()};
        qr.update(sql, params);
    }

    @Override
    public List<Syslog> findAll(int page, int size,String username) throws SQLException {
        QueryRunner qr = new QueryRunner(JdbcUtil.getDataSource());
        List<Syslog> syslogList=null;
        if(username!=null&&username!=""){
            String sql = "select * from syslog where username like concat('%',?,'%') limit ?,?";
            Object[] params = { username,page,size};
             syslogList= (List<Syslog>) qr.query(sql,params, new BeanListHandler(Syslog.class));
        }else {
            String sql = "select * from syslog limit ?,?";
            Object[] params = {page,size};
             syslogList= (List<Syslog>) qr.query(sql,params, new BeanListHandler(Syslog.class));
        }
        return syslogList;
    }

    @Override
    public void deleteSysLog() throws SQLException {
        QueryRunner qr = new QueryRunner(JdbcUtil.getDataSource());
        String sql = "truncate table syslog";
        qr.update(sql);
    }

    @Override
    public int getLogNum(String username) throws SQLException {
        QueryRunner qr = new QueryRunner(JdbcUtil.getDataSource());
        int syslogNum=0;
        if(username!=null&& !username.equals("")){
            String sql = "select count(*) from syslog where username like concat('%',?,'%')";
            Object[] params = { username};
            syslogNum= ((Long) qr.query(sql,params, new ScalarHandler(1))).intValue();
        }else {
            String sql = "select count(*) from syslog";
            syslogNum= ((Long) qr.query(sql, new ScalarHandler(1))).intValue();
        }
        return syslogNum;
    }
}
